import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI } from '@/api'
const getDefaultState = () => {
  return {
    token: getToken()
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
    removeToken()
  },
  SET_TOKEN (state, val) {
    state.token = val
    setToken(val)
  }
}

const actions = {
  // 登录
  async loginActions ({ commit }, loginForm) {
    // return new Promise((resolve, reject) => {
    //   loginAPI(loginForm).then(res => {
    //     commit('SET_TOKEN', res.data)
    //     resolve(res)
    //   }).catch(err => {
    //     reject(err)
    //   })
    // })
    try {
      const res = await loginAPI(loginForm)
      commit('SET_TOKEN', res.data)
      return res
    } catch (err) {
      return Promise.reject(err)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

